<template>
  <div class="my">
    <header>
      <div class="top">
        <van-image class="avatar" round width="60px" height="60px" fit="cover" :src="storeImgs()" />
        <div class="user_info">
          <div>
            <span class="name">{{mainStore.storeInfo.title}}</span>
          </div>
        </div>

        <div @click="exitStore" style="position: absolute;right: 0;top:0;">
          <img style="height: 25px" src="@/assets/img/video/exit.png" />
        </div>
        <van-button
            class="mySuperior"
            type="primary"
            v-if="mainStore.storeInfo.user_id"
            @click="state.mySuperiorShow = true"
        >
          <span>我的推荐人</span>
          <van-icon name="play-circle" />
        </van-button>
      </div>
      <van-grid class="card" :border="false" :column-num="checkRoles('4') ? 4 : 5">
        <van-grid-item class="card_item" @click="becomeVip">
          <div>
            <img style="height: 40px" src="@/assets/img/video/vip.jpg" />
          </div>
          <span>相亲之旅</span>
        </van-grid-item>
        <van-grid-item class="card_item" @click="navigationTo('verifiedMember')">
          <div>
            <img style="width: 34px; height: 27px" src="@/assets/img/video/video.png" />
          </div>
          <span>会员套餐</span>
        </van-grid-item>
        <van-grid-item class="card_item" @click="navigationTo('becomeMatchmaker')">
          <div>
            <img style="width: 30px; height: 30px" src="@/assets/img/my/matchmaker.png" />
          </div>
          <span>成为红娘</span>
        </van-grid-item>
      </van-grid>
    </header>

    <main>
      <van-grid class="card card2" :border="false">
        <van-grid-item  @click="navigationTo('evaluationTrain')">
          <img src="@/assets/img/my/evaluation_train.png" />
          <span>培训评价</span>
        </van-grid-item>
        <van-grid-item>
          <img src="@/assets/img/my/matchmaker_team.png" @click="navigationTo('team', 'store')" />
          <span>下级团队</span>
        </van-grid-item>
        <van-grid-item @click="navigationTo('storeIncomeDetails')">
          <img style="width: 43px; height: 43px" src="@/assets/img/my/earnings.png" />
          <span>门店收益</span>
        </van-grid-item>
      </van-grid>
    </main>

    <div style="padding: 0 15px; margin-bottom: 10px">
      <van-grid class="card card4" :border="false">
        <van-grid-item class="card_item" @click="navigationTo('incomeDetails')">
          <div>
            <img style="width: 26px; height: 24px" src="@/assets/img/my/earnings.png" />
          </div>
          <span>收益明细</span>
        </van-grid-item>
        <van-grid-item class="card_item" @click="navigationTo('withdrawal')">
          <div>
            <img style="width: 30px; height: 23px" src="@/assets/img/my/withdrawal.png" />
          </div>
          <span>提现申请</span>
        </van-grid-item>
        <van-grid-item class="card_item" @click="navigationTo('accountManage')">
          <div>
            <img style="width: 25px; height: 25px" src="@/assets/img/my/account.png" />
          </div>
          <span>账号管理</span>
        </van-grid-item>
        <van-grid-item class="card_item" @click="navigationTo('withdrawalRecord')">
          <div>
            <img style="width: 23px; height: 24px" src="@/assets/img/my/withdrawal_record.png" />
          </div>
          <span>提现记录</span>
        </van-grid-item>
      </van-grid>
    </div>

    <footer style="padding: 0 15px 10px 15px">
      <div class="card card3">
        <van-cell is-link @click="navigationTo('order')">
          <template #title>
            <img src="@/assets/img/my/cell_icon5.png" />
            <span class="custom-title">我的订单</span>
          </template>
        </van-cell>
      </div>
    </footer>

    <footer>
      <div class="card card3">
        <van-cell is-link @click="navigationTo('aboutUs')">
          <template #title>
            <img src="@/assets/img/my/cell_icon1.png" />
            <span class="custom-title">关于我们</span>
          </template>
        </van-cell>
        <van-cell is-link @click="navigationTo('question')">
          <template #title>
            <img src="@/assets/img/my/cell_icon2.png" />
            <span class="custom-title">疑问解答</span>
          </template>
        </van-cell>
        <van-cell is-link @click="navigationTo('messageRecords')">
          <template #title>
            <img src="@/assets/img/my/cell_icon3.png" />
            <span class="custom-title">留言咨询</span>
          </template>
        </van-cell>
        <!--				<van-cell>-->
        <!--					<template #title>-->
        <!--						<img src="@/assets/img/my/cell_icon4.png" />-->
        <!--						<span class="custom-title">我要找对象</span>-->
        <!--					</template>-->
        <!--					<template #right-icon>-->
        <!--						<div class="switch_box" v-debounce="switchState">-->
        <!--							<van-switch v-model="switchChecked" size="22px" active-color="#F53D7D" inactive-color="#EEEDED" />-->
        <!--						</div>-->
        <!--					</template>-->
        <!--				</van-cell>-->
        <van-cell is-link @click="navigationTo('guide')">
          <template #title>
            <img src="@/assets/img/video/zhinan.png" />
            <span class="custom-title">防骗指南</span>
          </template>
        </van-cell>
        <van-cell
            @click="playVideo()"
        >
          <template #title>
            <img src="@/assets/img/video/shipin.png" />
            <span class="custom-title">教学视频</span>
          </template>
        </van-cell>
      </div>
    </footer>

    <MyTabbar />

    <!-- 开通套餐会员弹窗 -->
    <vipPopup ref="vipPopupRef" @openVipPackage="openVipPackage" />

    <!-- 我的上级弹窗 -->
    <mySuperiorPopup v-model:show="state.mySuperiorShow" :item="mainStore.storeInfo?.store_parent_user" />

    <!-- 推广码 -->
    <prome-code v-model:show="state.codeShow" :posterImgPath="state.posterImgPath" />

    <!-- 推广码权益 -->
    <MyDialogBtn v-model:show="state.codeDialogShow" column>
      <template #content>
        <div style="max-height: 50vh; overflow: scroll">
          <div style="margin-bottom: 30px">分享权益</div>
          <p v-html="state.promote_contents" style="font-size: 13px; text-align: left; line-height: 24px"></p>
        </div>
      </template>
      <template #btn>
        <van-button type="primary" @click="getGeneratePosters">确定</van-button>
      </template>
    </MyDialogBtn>

    <!--  教学视频-->
    <van-popup v-model:show="show" :closeable="state.closeable" close-icon="close" style="background: none" @close="popupClose">
      <div class="popup_content">
        <video ref="videoRef"
               controls
               webkit-playsinline
               playsinline
               disablePictureInPicture="true"
               controlslist="nodownload noremoteplayback"
               :src="state.short_video"></video>
      </div>
    </van-popup>
  </div>
</template>
<script lang="ts" setup>
import { useMainStore } from '@/store';
import {computed, nextTick, onMounted, reactive, ref, toRefs} from "vue";
import {useRouter} from "vue-router";
import {Toast} from "vant";
import {generatePosters, updateMemberState} from "@/api/my";
import vipPopup from "@/views/index/components/vipPopup.vue";
import {createVipOrder} from "@/api";
import {getWxConfig, globalConfigValue, memberInfo, wxVipPay} from "@/api/common";
import wxApiReady from "@/hooks/wxApiReady";
import wx from "weixin-jsapi";
import useAuthorize from "@/hooks/authorize";
import showVip from '@/hooks/showVip';
import userCenter from '@/views/my/userCenter.vue'
import storeCenter from '@/views/my/storeCenter.vue'
import promeCode from '@/views/my/components/promoCode.vue';
import mySuperiorPopup from '@/views/my/components/mySuperiorPopup.vue';

const siteTitle = import.meta.env.VITE_SITE_TITLE;
const imgUrl = import.meta.env.VITE_IMG_URL;
const siteDomain = import.meta.env.VITE_DOMAIN;
const mainStore = useMainStore();
const router = useRouter();
const state = reactive<any>({
  mySuperiorShow: false,
  posterImgPath: '',
  codeDialogShow: false,
  codeShow: false,
  checked: false,
  closeable: true,
  info: {},
  store: {},
  promote_contents: '',
  short_video: '',
});
const { info } = toRefs(state);

let show = ref(false);
const videoRef = ref<HTMLVideoElement | null>(null);

const playVideo = () => {
  nextTick(() => {
    videoRef.value?.play();
  })
  show.value = true;
};


// 弹窗关闭 暂停视频
const popupClose = () => {
  if (!videoRef.value?.paused) {
    videoRef.value?.pause();
  }
};

onMounted(() => {
  getGlobalConfigValue();
  getGlobalConfigValueByShortVideo();
  getMemberInfo();
  initShare();
});

const checkRoles = (key: string): boolean => {
  return String(mainStore.userInfo?.identity).split(',').includes(key);
};

const switchChecked = computed<boolean>(() => {
  return mainStore.userInfo?.is_disabled ? false : true;
});

// 退出门店
const exitStore = () => {
  mainStore.storeIsLogin = false;
  mainStore.storeInfo = null;
}

// 门店头像
const storeImgs = () : string => {
  if (mainStore.storeIsLogin) {
    if (mainStore.storeInfo.storeimgs) {
      return imgUrl + mainStore.storeInfo.storeimgs
    } else {
      return state.info.head_img_url
    }
  } else {
    return state.info.head_img_url
  }
}

// 打开海报图
const openPosterPopup = () => {
  if (typeof mainStore.userInfo.audit_state != 'undefined' && mainStore.userInfo.audit_state != 1) {
    if (mainStore.userInfo.audit_state == 0) return Toast('您的资料正在审核中');
    if (mainStore.userInfo.audit_state == 2) return Toast('未通过：'+mainStore.userInfo.audit_msg);
  }
  state.codeDialogShow = true;
}

// 获取海报图
const getGeneratePosters = async () => {
  state.codeDialogShow = false;
  Toast.loading({
    message: '正在加载中...',
    forbidClick: true,
  });
  const res = await generatePosters({
    user_id:mainStore.user_id,
    shareLink: `https://ztcy.huimaibuy.com/h5/#/index?parent_id=${mainStore.user_id}`
  });
  state.posterImgPath = res.data.posterImgPath;
  state.codeShow = true;
};

// 导航跳转
const navigationTo = (name: string, type?: string): any => {
  console.log('name',name);
  // 白名单菜单
  let menuList = [
    'registered',
    'payRecord',
    'viewRecord',
    'collection',
    'team',
    'incomeDetails',
    'withdrawal',
    'accountManage',
    'withdrawalRecord',
    'aboutUs',
    'question',
    'messageRecords',
    'guide',
  ];
  if (!menuList.includes(name)) {
    if (typeof mainStore.userInfo.audit_state != 'undefined' && mainStore.userInfo.audit_state != 1) {
      if (mainStore.userInfo.audit_state == 0) return Toast('您的资料正在审核中');
      if (mainStore.userInfo.audit_state == 2) return Toast('未通过：'+mainStore.userInfo.audit_msg);
    } else {
      if (checkRoles('0')) {
        if (name === 'becomeMatchmaker' || name === 'becomeVip' || name === 'verifiedMember' || name === 'joinStores' || name === 'storeLogin') {
          Toast({
            message : '您还不是注册用户，请先完成注册',
            duration : 2000
          });
        }
      }
      console.log('identity',mainStore.userInfo?.identity)
      if ((!mainStore.userInfo?.identity || mainStore.userInfo?.identity == '0')) {
        router.push('/registered');
        return;
      }
      if ((!mainStore.userInfo?.state || mainStore.userInfo?.state == '0')) {
        router.push('/registered');
        return;
      }
    }
  }
  if (name === 'registered') {
    if (mainStore.userInfo.audit_state == 2 || mainStore.userInfo.audit_state == 1) {
      router.push({ name, query: { isEdit: 1 } });
      return;
    }
  }
  if (name === 'team' && type) {
    router.push({ name, query: { type } });
    return;
  }
  router.push({ name });
};

// 更新找对象状态
const switchState = async (): Promise<any> => {
  if (typeof mainStore.userInfo.audit_state != 'undefined' && mainStore.userInfo.audit_state != 1) {
    if (mainStore.userInfo.audit_state == 0) return Toast('您的资料正在审核中');
    if (mainStore.userInfo.audit_state == 2) return Toast('未通过：'+mainStore.userInfo.audit_msg);
  } else {
    if ((!mainStore.userInfo?.identity || mainStore.userInfo?.identity == '0')) {
      router.push('/registered');
      return;
    }
    if ((!mainStore.userInfo?.state || mainStore.userInfo?.state == '0')) {
      router.push('/registered');
      return;
    }
  }
  const res = await updateMemberState({
    user_id: mainStore.user_id,
    is_disabled: mainStore.userInfo?.is_disabled == 1 ? 0 : 1
  });
  await getMemberInfo();
};

const vipPopupRef = ref<InstanceType<typeof vipPopup> | null>(null);
const becomeVip = () => {
  return Toast({
    message : '正在开发中',
    duration : 2000
  });
  if (typeof mainStore.userInfo.audit_state != 'undefined' && mainStore.userInfo.audit_state != 1) {
    if (mainStore.userInfo.audit_state == 0) return Toast('您的资料正在审核中');
    if (mainStore.userInfo.audit_state == 2) return Toast('未通过：'+mainStore.userInfo.audit_msg);
  } else {
    if (checkRoles('0')) {
      Toast({
        message : '您还不是注册用户，请先完成注册',
        duration : 2000
      });
    }
    if ((!mainStore.userInfo?.identity || mainStore.userInfo?.identity == '0')) {
      router.push('/registered');
      return;
    }
    if ((!mainStore.userInfo?.state || mainStore.userInfo?.state == '0')) {
      router.push('/registered');
      return;
    }
  }
  vipPopupRef.value!.showPopup();
};

// 开通vip套餐
const openVipPackage = async (currentPackage: any) => {
  const packageParams = {
    user_id: mainStore.user_id,
    vip_id: currentPackage.id,
    amount: currentPackage.price
  };
  // 创建vip套餐订单
  const res = await createVipOrder(packageParams);
  const oid: number = res.data;
  Toast.loading({
    message: '加载中...',
    forbidClick: true,
  });
  const params: any = await wxVipPay(oid);
  wxApiReady(['chooseWXPay'])
      .then((res) => {
        wx.chooseWXPay({
          timestamp: params.timeStamp, // 支付签名时间戳，注意微信 jssdk 中的所有使用 timestamp 字段均为小写。但最新版的支付后台生成签名使用的 timeStamp 字段名需大写其中的 S 字符
          nonceStr: params.nonceStr, // 支付签名随机串，不长于 32 位
          package: params.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
          signType: params.signType, // 微信支付V3的传入 RSA ,微信支付V2的传入格式与V2统一下单的签名格式保持一致
          paySign: params.paySign, // 支付签名
          success: async (result: object) => {
            // 支付成功后的回调函数
            console.log(result);
            Toast.success('支付成功');
            vipPopupRef.value!.closePopup();
            setTimeout(() => {
              getMemberInfo();
            }, 2000);
          }
        });
      })
      .catch((err) => console.log(err));
};

// 获取用户信息
const getMemberInfo = async (): Promise<void> => {
  const res = await memberInfo(mainStore.user_id);
  if (res.errorCode == 0 && res.data) {
    state.info = res.data;
    mainStore.userInfo = res.data;
    state.store = res.data.store;
  } else if (res.errorCode == 1) {
    Toast(res.errorInfo);
    mainStore.userInfo = null;
    useAuthorize();
  }
};

// 推广码内容
const getGlobalConfigValue = async () => {
  const promoteContents = mainStore.promoteContents
  if (promoteContents == null) {
    const res = await globalConfigValue('promote_contents');
    state.promote_contents = res.data.item_value;
    mainStore.promoteContents = res.data.item_value;
  } else {
    state.promote_contents = promoteContents
  }
};

// 教学视频
const getGlobalConfigValueByShortVideo = async () => {
  const shortVideoUrl = mainStore.shortVideoUrl;
  if (shortVideoUrl == null) {
    const res = await globalConfigValue('short_video');
    state.short_video = imgUrl + res.data.item_value;
    mainStore.shortVideoUrl = imgUrl + res.data.item_value;
  } else {
    state.short_video = shortVideoUrl
  }
};

// 分享
const initShare = async (update:boolean = false) => {
  const wxConfig = mainStore.wxConfig;
  console.log('wxConfig：',wxConfig)
  if (wxConfig == null || update) {
    const configRes = await getWxConfig();
    mainStore.wxConfig = configRes.data;
  }
  const { appId, timestamp, nonceStr, signature } = mainStore.wxConfig;
  let jsApiList = ['onMenuShareAppMessage', 'onMenuShareTimeline'];
  wx.config({
    debug: false,
    appId,
    timestamp,
    nonceStr,
    signature,
    jsApiList
  });
  wx.ready(() => {
    wx.onMenuShareAppMessage({
      title: siteTitle, // 分享标题
      desc: siteTitle, // 分享描述
      link: `https://ztcy.huimaibuy.com/h5/#/index`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致
      imgUrl: mainStore.userInfo.head_img_url, // 分享图标
      type: 'link', // 分享类型,music、video或link，不填默认为link
      dataUrl: '', // 如果 type 是music或video，则要提供数据链接，默认为空
      success: async () => {
        // 用户点击了分享后执行的回调函数
      },
      cancel: (res: any) => {
        console.log(res);
      }
    });
    wx.onMenuShareTimeline({
      title: siteTitle, // 分享标题
      link: `https://ztcy.huimaibuy.com/h5/#/index`,
      imgUrl: mainStore.userInfo.head_img_url, // 分享图标
      success: async () => {
        // 用户点击了分享后执行的回调函数
      },
      cancel: (res: any) => {
        console.log(res);
      }
    });
  });
  wx.error((res:any) => {
    console.log('err', res)
  });
};
</script>
<style lang="scss" scoped>
//:deep(.van-popup) {
//  .van-icon {
//    background: white;
//    border-radius: 10px;
//  }
//}
:deep(.van-grid) {
  .van-grid-item {
    &:active {
      background: #f7f7f7;
    }
    .van-grid-item__content {
      background: none;
    }
  }
}
.my {
  min-height: 100vh;
  overflow: scroll;
  background: #f5f5f5;
  padding-bottom: env(safe-area-inset-bottom);
  .card {
    overflow: hidden;
    color: #555d7a;
    font-size: 11px;
    font-weight: 500;
    border-radius: 15px;
    box-shadow: 0px 3px 9px 0px rgba(123, 123, 123, 0.08);
    background: white;
    .card_item {
      div {
        @include flx-center;
        height: 30px;
        margin-bottom: 10px;
      }
    }
  }
  .card2 {
    color: #454d65;
    font-size: 12px;
    font-weight: 500;

    img {
      width: 43px;
      height: 43px;
      margin-bottom: 10px;
    }
  }
  .card3 {
    padding: 0;
  }

  header {
    @include flx-direction-between;
    width: 100%;
    height: 230px;
    box-sizing: border-box;
    padding: 40px 15px 0 15px;
    margin-bottom: 10px;
    color: white;
    background-image: url('@/assets/img/my/my_bg.png');
    background-repeat: no-repeat;
    background-size: cover;
    .top {
      @include flx-align-center;
      position: relative;
      .user_info {
        @include flx-direction-between;
        margin-left: 15px;
        font-size: 12px;
        div {
          @include flx-align-center;
          margin-bottom: 8px;
          .vip {
            width: 16px;
            height: 14px;
            margin-left: 10px;
          }
          .certification {
            width: 54px;
            height: 20px;
            margin-left: 10px;
          }
          .identity {
            margin-left: 10px;
            background-color: white;
            border-radius: 22px;
            color: #F74E89;
            padding: 0 10px;
            font-size: 10px;
            line-height: 22px;
            height: 22px;
          }
        }
        .name {
          font-size: 18px;
          font-weight: bold;
        }
      }
      .mySuperior {
        @include flx-justify-between;
        position: absolute;
        right: 0;
        bottom: 0;
        height: 26px;
        padding: 0 12px;
        color: #f6518a;
        font-size: 12px;
        border: none;
        border-radius: 15px;
        background: white;
        span {
          margin-right: 3px;
        }
      }
    }
  }
  main {
    padding: 0 15px;
    margin-bottom: 10px;
    :deep(.van-grid) {
      & > :nth-child(-n + 4) {
        .van-grid-item__content {
          padding-bottom: 8px;
        }
      }
      & > :nth-child(n + 5) {
        .van-grid-item__content {
          padding-top: 8px;
        }
      }
    }
  }
  footer {
    padding: 0 15px 65px 15px;
    :deep(.van-cell) {
      height: 55px;
      line-height: 55px;
      padding: 0 15px;
      .van-badge__wrapper {
        line-height: 55px;
      }
      .van-cell__title {
        @include flx-align-center;
      }
      img {
        width: 15px;
        height: 15px;
        margin-right: 8px;
      }
      .custom-title {
        color: #343434;
        font-size: 14px;
        font-weight: 400;
      }
      .switch_box {
        @include flx-center;
      }
    }
  }

  .popup_content {
    width: 100vw;
    height: 100vh;
    overflow: hidden;
    video {
      width: 100%;
      height: 100%;
      object-fit: contain;
      //border-radius: 20px;
    }
  }
}
</style>